// pages/home/home.js
const app = getApp();
var swiperHeight;
import http from '../../utils/http.js';
import {
  noticeDetail
} from '../../utils/notice.js';
const messageType = {
  'remind': '提醒',
  'info': '消息',
  'warning': '警告',
  'hotspot': '热点'
}
Page({
  data: {
    imgUrls: [{
      image: '/images/banner/banner2.png',
    }],
    userinfo: null,
    isBind: app.globalData.isBindWx,
    indicatorDots: true,
    circular: true,
    autoplay: true,
    interval: 3000,
    duration: 500,
    navMenu: app.globalData.navMenu,
    navList: [],
    scrollFlag: false,
    islogin: null,
    swiperIndex: 0, // 滚动消息
    msgCount: 5, // 消息总数
    msgSwiperHeight: 0,
    isShow: true,
    msgList: [],
    topList: [],
    isShowData: false
  },
  // 获取轮播图
  getSwiperImages: function() {
    http.request({
      url: '/findWxCarousel',
      data:{
        carouselType: 0
      },
      success: (res) => {
        let imgUrls = res;
        for (let i = 0; i < res.length; i++) {
          let src = http.apiUrl + http.imgUrl + "?imagePath=" + res[i].image +
            "&" + wx.getStorageSync("sessionid")
          imgUrls[i].image = encodeURI(src);
        }
        this.setData({
          imgUrls: imgUrls
        }) 
      },
    });
  },
  // 轮播图跳转
  goDetail: function(e) {
    let imgUrls = this.data.imgUrls;
    let id = e.currentTarget.dataset.id
    if (id >1 ){
    wx.navigateTo({
      url: './imageDetail/imageDetail?id=' + id,
    })
    }
  },
  loadNotice: function() {
    //页面加载去读取消息中心，步骤如下
    //1、先从微信获取授权状态，判断是否已经做了微信授权
    //2、如果已授权，从自己服务器后台获取登录后的token（即sessionId)
    //3、做完上两步操后读取消息
    wx.getUserInfo({
      success: detail => {
        wx.login({
          success: res => {
            if (res.errMsg == "login:ok") {
              let data = {
                wxLogin: 'true', //使用微信登录标志，不需要再输入用户名密码，直接可通过微信登录
                iv: detail.iv, //公钥
                encryptedData: detail.encryptedData, //加密的信息
                jsCode: res.code //通过wx.login获取的jsCode
              };
              wx.request({
                url: http.apiUrl + "/login", //自己的后台登录方法（即cortroller层的登录方法地址）
                method: 'POST',
                data: data,
                header: {
                  'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                success: (res) => {
                  if (res.data.code == 200) {
                    //说明登录成功
                    wx.setStorageSync("sessionid", res.header["Set-Cookie"].split(";")[0]);
                    this.getNotice();
                    http.request({
                      url: "/member/findMemberUserInfo", //自己的后台登录方法（即cortroller层的登录方法地址）
                      success: function(result) {
                        wx.setStorageSync("userInfo", result);
                      }
                    })
                  } else {
                    this.getNotice();
                  }
                }
              });
            }
          },
          fail: res =>{
            this.getNotice();
          }
        });
      },
      fail: res => {
        this.getNotice();
      }
    });
  },
  setTimeData: function() {
    this.loadNotice();
    setInterval(() => {
      this.loadNotice();
    }, 3600000);
  },
  //消息跳转
  msgDetail: function(e) {
    let id = e.currentTarget.dataset.id;
    let type = e.currentTarget.dataset.type;
    let title = "";
    let content = "";
    let time = "";
    let detail = e.currentTarget.dataset;
    title = e.currentTarget.dataset.title;
    content = e.currentTarget.dataset.content;
    time = e.currentTarget.dataset.time;
    noticeDetail.setValue(detail);
    if (type === "hotspot") {
      wx.navigateTo({
        url: './msgDetail/msgDetail',
      })
    } else {
      wx.showModal({
        title: title,
        content: content,
        showCancel: false,
      })
    }
  },
  // 获取消息列表
  getNotice: function() {
    http.request({
      url: '/findNotice',
      success: (res) => {
        let topList = [];
        let msgList = [];
        let isShowData = this.data.isShowData;
        if (res.length > 0) {
          isShowData = true;
          for (let i = 0; i < res.length; i++) {
            if (res[i].roof === 1) {
              res[i].typeCn = messageType[res[i].type];
              topList.push(res[i]);
            } else {
              res[i].typeCn = messageType[res[i].type];
              msgList.push(res[i]);
            }
          }
          let topListLength = topList.length; // 置顶消息长度
          // let swiperIndex = msgList.length; // 热点消息长度
          let msgListLength = msgList.length; // 热点消息长度
          let swiperIndex = 0;
          // 置顶消息长度大于总数量，滚动消息清空，不做轮播
          if (topListLength >= this.data.msgCount) {
            msgList=[];
            swiperIndex = 0;
          }else if(topListLength< this.data.msgCount){
            swiperIndex = this.data.msgCount - topListLength;
            if (swiperIndex > msgList.length){
              swiperIndex = msgList.length;
            }
          }
          this.setData({
            isShowData: isShowData,
            swiperIndex: swiperIndex,
            msgSwiperHeight: swiperIndex * 35,
            topList: topList,
            msgList: msgList
          })
        }
        // console.info(swiperIndex);
      },
    });
  },
  // 页面加载
  onLoad(options) {
    let _this = this;
    this.setTimeData();
    wx.getStorage({
      key: 'userInfo',
      success(res) {
        // console.log('success')
        if (res.data) {
          // console.log(res.data)
          _this.setData({
            userinfo: res.data,
            navList: res.data.wxFunc
          })
        }
      },
      fail(res) {
        _this.setData({
          userinfo: null,
          navList: null
        })
        wx.showToast({
          title: '进行登录可使用更多功能',
          icon: "none",
          duration: 2000
        })
      }
    })
  },

  onShow: function() {
    let _this = this;
    _this.getSwiperImages();
    //_this.getNotice();
    wx.getStorage({
      key: 'userInfo',
      success(res) {
        if (res.data) {
          _this.setData({
            userinfo: res.data,
            navList: res.data.wxFunc
          })
        }
      },
      fail(res) {
        _this.setData({
          userinfo: null,
          navList: null
        })
        wx.showToast({
          title: '进行登录可使用更多功能',
          icon: "none",
          duration: 2000
        })

      }
    })

    // _this.setData({
    //   userinfo: wx.getStorageSync('userInfo')
    // })
    // //console.log(that.data.userinfo)
    // //从缓存中取用户的功能菜单
    // _this.setData({
    //   navList: _this.data.userinfo.wxFunc,

    // })

  },

  //navigateTo 首页跳转
  navigateTo: function(event) {
    // console.log(event);
    let navMenu = this.data.navMenu;
    let len = navMenu.length;
    let itemCode = event.currentTarget.dataset.id;
    let name = event.currentTarget.dataset.title;
    for (let i = 0; i < len; i++) {
      if (navMenu[i].code == itemCode) {
        wx.navigateTo({
          url: navMenu[i].path + '?type=' + navMenu[i].type // 页面 B
        });
        wx.setNavigationBarTitle({
          title: name
        })
      }
    }
    // wx.navigateTo({
    //   url: '/pages/trade/trade'　 // 页面 B
    // });
    // wx.setNavigationBarTitle({
    //   title: name
    // })

  },
  goLogin() {
    wx.navigateTo({
      url: '/pages/me/login/login',
    })

  },
  // 监听滚动条改变搜索框背景
  onPageScroll({
    scrollTop: val
  }) {
    wx.createSelectorQuery()
      .selectAll('.swiper-item')
      .boundingClientRect(rect => {
        swiperHeight = rect[0].height
      }).exec()

    if (val >= swiperHeight) {
      this.setData({
        scrollFlag: true
      })
    } else {
      this.setData({
        scrollFlag: false
      })
    }
  }
})